import React, { useEffect, useState } from "react";
import { Link, withRouter } from "react-router-dom";
import { Button, Container, Form, FormGroup, Input, Label } from "reactstrap";
import AppNavbar from "./appNavbar";

const ClientEdit = (props) => {
  const [count, setCount] = useState(0);
  const [person, setPerson] = useState({ id: 0, name: "", email: "" });

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    if (props.match.params.id !== "new") {
      const id = props.match.params.id;
      const response = await fetch(`/clients/${id}`);
      const body = await response.json();
      console.log(body); //这个log会打印2次？？
      setPerson(body);
      console.log(person); //取到的还是初始化的默认变量？
    }
  };

  const handleChange = (event) => {
    console.log(event);
    const { name, value } = event.target;
    setPerson({ ...person, [name]: value });
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    await fetch("/clients" + (person.id ? "/" + person.id : ""), {
      method: person.id ? "PUT" : "POST",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json",
      },
      body: JSON.stringify(person),
    });

    props.history.push("/clients");
  };

  const title = <h2>{person.id ? "Edit Client" : "Add Client"}</h2>;
  return (
    <div>
      <AppNavbar />
      <Container>
        {title}
        <Form onSubmit={handleSubmit}>
          <FormGroup>
            <Label for="name">Name</Label>
            <Input
              type="text"
              name="name"
              id="name"
              onChange={handleChange}
              autoComplete="name"
              value={person.name || ""}
            />
          </FormGroup>
          <FormGroup>
            <Label for="email">Email</Label>
            <Input
              type="text"
              name="email"
              id="email"
              onChange={handleChange}
              autoComplete="email"
              value={person.email || ""}
            />
          </FormGroup>
          <FormGroup>
            <Button color="primary" type="submit">
              Save
            </Button>
            <Button color="secondary" tag={Link} to="/clients">
              Cancel
            </Button>
          </FormGroup>
        </Form>
      </Container>
    </div>
  );
};

export default withRouter(ClientEdit);
